package com.hexacta.hrs.web.struts.actions.feedbacks;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.vectrics.employee.Employee;
import org.vectrics.user.Person;

import com.hexacta.hrs.domain.feedback.ArchivoAdjunto;
import com.hexacta.hrs.domain.feedback.FeedbackPeriod;
import com.hexacta.hrs.services.employee.EmployeeService;
import com.hexacta.hrs.services.feedbacks.FeedbackPeriodService;
import com.hexacta.hrs.services.person.PersonService;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction extends ActionSupport {

    private boolean readOnly = false;

    private PersonService personService;

    private EmployeeService employeeService;

    private FeedbackPeriodService feedbackPeriodService;

    private static final long serialVersionUID = -7535990010257964723L;

    private static String SELFEVALUATION = "uploadAutoevaluation";

    private static String DISCHARGE = "uploadDischarge";

    // private File upload;// The actual file
    // private String uploadContentType; // The content type of the file
    // private String uploadFileName; // The uploaded file name
    private List<File> fileUpload = new ArrayList<File>();

    private List<String> fileUploadContentType = new ArrayList<String>();

    private List<String> fileUploadFileName = new ArrayList<String>();

    private String selectedOption;

    public String uploadAutoevaluation() {
        selectedOption = SELFEVALUATION;
        return SELFEVALUATION;

    }

    public String uploadDischarge() {
        selectedOption = DISCHARGE;
        return DISCHARGE;

    }

    public String save() {

        try {
        	 if (validateFile()){
        		 return selectedOption;
        	 }else{
        		 for (int i = 0; i < fileUpload.size(); i++) {
        			 if (!fileUploadFileName.get(i).equals("")) {
        				 String fullFileName = "c:/upload/" + fileUploadFileName.get(i);
        				 File uploadedFile = new File(fullFileName);
        				 FileUtils.copyFile(fileUpload.get(i), uploadedFile);

        				 Employee employee = getEmployee(i);

        				 ArchivoAdjunto file = new ArchivoAdjunto();
        				 Calendar cal = Calendar.getInstance();

						file.setFechaUpload(cal.getTime());
						file.setContentType("application/msword");
						file.setNombre(fileUploadFileName.get(i));
						file.setBytes(FileUtils.readFileToByteArray(uploadedFile));
						FeedbackPeriod period = employee.getCurrentFeedbackPeriod();

						if (period == null) {
							addActionError("There is no currently open feedback period for "
									+ employee.getPerson().getFullName());
							return selectedOption;
						} else {
							if (DISCHARGE.equals(selectedOption)) {
								period.setDischarge(file);
							} else if (SELFEVALUATION.equals(selectedOption)) {
								period.setSelfevaluation(file);
							}

							feedbackPeriodService.update(period);
							employeeService.update(employee);
						}
					}
				}
			}
        } catch (Exception e) {
          	if (fileUpload.size() == 1) {
        		addActionError("The file is empty");
    		}else{
            e.printStackTrace();
            addActionError(e.getMessage());
    		}
          	return selectedOption;
        }
        return SUCCESS;

    }
    
    public boolean validateFile() {
    	boolean errors = false;
        if (fileUpload.size() > 0) {
            for (int i = 0; i < fileUpload.size(); i++) {

                if (!getFileExtension(i).equals("doc") && !getFileExtension(i).equals("docx")) {
                    addFieldError("File"+i,"File" + i + " type is wrong, must be .doc or .docx");
                    errors = true;
                }

                if (!isValidFileName(i)) {
                    addFieldError("File"+i, "File" + i + " name is invalid, must have the format (Email Username).docx");
                    errors = true;
                }

                if (isValidFileName(i)) {
                    if (getEmployee(i) == null) {
                    	addFieldError("File"+i,"Employee not found, make sure the file" + i+ " name is correct");
                        errors = true;
                    }
                }
                
            }
        }
        return errors;
    }

    private boolean isValidFileName(final int i) {
        return getOnlyFileName(i).matches("^(\\w+)$");
    }

    private Employee getEmployee(final int i) {

        String email = getOnlyFileName(i) + "@hexacta.com";
        Person person = personService.getPersonByEmail(email);
        if (person != null) {
            Employee employee = employeeService.searchByPerson(person);
            if (employee != null) {
                System.out.println("Employee " + employee.getTitle());
                return employee;
            }
        }

        return null;
    }

    private String getName(final int i) {
        String[] names = fileUploadFileName.get(i).split("_");
        return names[0];

    }

    private String getLastName(final int i) {
        String[] names = fileUploadFileName.get(i).split("_");
        return names[1].split("\\.")[0];
    }

    private String getFileExtension(final int i) {
        return fileUploadFileName.get(i).split("\\.")[1];
    }

    private String getOnlyFileName(final int i) {
        return fileUploadFileName.get(i).split("\\.")[0];
    }

    public List<File> getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(final List<File> fileUpload) {
        this.fileUpload = fileUpload;
    }

    public List<String> getFileUploadContentType() {
        return fileUploadContentType;
    }

    public void setFileUploadContentType(final List<String> fileUploadContentType) {
        this.fileUploadContentType = fileUploadContentType;
    }

    public List<String> getFileUploadFileName() {
        return fileUploadFileName;
    }

    public void setFileUploadFileName(final List<String> fileUploadFileName) {
        this.fileUploadFileName = fileUploadFileName;
    }

    public PersonService getPersonService() {
        return personService;
    }

    public void setPersonService(final PersonService personService) {
        this.personService = personService;
    }

    public EmployeeService getEmployeeService() {
        return employeeService;
    }

    public void setEmployeeService(final EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    /**
     * @return the feedbackPeriodService
     */
    public FeedbackPeriodService getFeedbackPeriodService() {
        return feedbackPeriodService;
    }

    /**
     * @param feedbackPeriodService
     *            the feedbackPeriodService to set
     */
    public void setFeedbackPeriodService(final FeedbackPeriodService feedbackPeriodService) {
        this.feedbackPeriodService = feedbackPeriodService;
    }

    /**
     * @return the readOnly
     */
    public boolean isReadOnly() {
        return readOnly;
    }

    /**
     * @param readOnly
     *            the readOnly to set
     */
    public void setReadOnly(final boolean readOnly) {
        this.readOnly = readOnly;
    }

    /**
     * @return the selectedOption
     */
    public String getSelectedOption() {
        return selectedOption;
    }

    /**
     * @param selectedOption
     *            the selectedOption to set
     */
    public void setSelectedOption(final String selectedOption) {
        this.selectedOption = selectedOption;
    }

}